const stream = require('stream');
import {parseTime} from "@/utils/ruoyi";

const Minio = require('minio')

const minioClient = new Minio.Client({
  endPoint: '59.110.170.159',
  port: 9000,
  useSSL: false,
  accessKey: 'BY9yavzcdzMtgQzTF6LZ',
  secretKey: 'dreRgjSYo6A4KV4yJTMjtstZ9xJNa8H9LlggjWXO',
})
//亚太
// const minioClient = new Minio.Client({
//   endPoint: '116.62.132.131',
//   port: 9000,
//   useSSL: false,
//   accessKey: 'ZHWvlbebnIBW1eHV3b8r',
//   secretKey: 'q6ldTlrlslr5LFZXSot003xFeMmr7DzirDluyvd8',
// })

export function ossClient() {
  return minioClient;
}

//base64转blob
function toBlob(base64Data) {
  let byteString = base64Data
  if (base64Data.split(',')[0].indexOf('base64') >= 0) {
    byteString = window.atob(base64Data.split(',')[1])
  } else {
    byteString = unescape(base64Data.split(',')[1])
  }
  const mineString = base64Data.split(';')[0].split(':')[1]
  const uintArr = new Uint8Array(byteString.length)
  for (let i = 0; i < byteString.length; i++) {
    uintArr[i] = byteString.charCodeAt(i)
  }
  const blob = new Blob([uintArr], {type: mineString})
  return blob
}

export function putFile(bucketName, file, error, success, progress) {
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onloadend = function (e) {
    const dataUrl = e.target.result
    const blob = toBlob(dataUrl)
    const reader2 = new FileReader()
    reader2.readAsArrayBuffer(blob)
    reader2.onload = function (ex) {
      const bufferStream = new stream.PassThrough()
      bufferStream.end(Buffer.from(ex.target.result))
      const metaData = {
        'content-type': file.type,
        'content-length': file.size
      }
      const time = new Date().getTime()
      const fileDate = parseTime(time, '{y}{m}{d}')
      const filePath = `${fileDate}/${time}_${file.name}`
      minioClient.putObject(bucketName, filePath, bufferStream, file.size, metaData, err => {
        if (err == null) {
          minioClient.presignedPutObject(bucketName, filePath, 24 * 60 * 60, (err2, presignedUrl) => {
            if (err2) return error(err2)
            createUploadHttp(file, presignedUrl, filePath, progress, success)
          })
        } else {
          error(err)
        }
      })
    }
  }
}

//上传文件
export function uploadFile(fileObj, error, success, progress) {
  const file = fileObj
  if (file) {
    const bucketName = 'threedegree'
    minioClient.bucketExists(bucketName, err => {
      if (err) {
        minioClient.makeBucket(bucketName,err1 => {
          if (err1) return error(err1)
          putFile(bucketName, file, error, success, progress)
        })
      }
      putFile(bucketName, file, error, success, progress)
    })
  }
}

//下载文件
export function downloadFile(filePath, callback) {
  const bucketName = 'threedegree'
  minioClient.getObject(bucketName, filePath, (err, dataStream) => {
    if (err) callback(err)
    const arr = []
    let size = 0
    dataStream.on('data', chunk => {
      if (chunk.length > 0) {
        arr.push(chunk)
        size += chunk.length
      }
    })
    dataStream.on('end', () => {
      const u8arr = new Uint8Array(size)
      let u8arrIndex = 0
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr[i].length; j++) {
          u8arr[u8arrIndex] = arr[i][j]
          u8arrIndex += 1
        }
      }
      const arrBuffer = u8arr.buffer
      const blob = new Blob([arrBuffer])
      const blobUrl = URL.createObjectURL(blob)
      const fileName = filePath.subString(filePath.indexOf('_'))
      const a = document.createElement('a')
      a.setAttribute('href', blobUrl)
      a.setAttribute('download', fileName)
      a.click()
    })
    dataStream.on('error', er => {
      callback(er)
    })
  })
}

//获取上传进度
export function createUploadHttp(file, filePutUrl, filePath, progress, success) {
  const http = new XMLHttpRequest()
  http.upload.addEventListener('progress', e => {
    const num = (e.loaded / e.total).toFixed(2)
    const str = (Number(num) * 100).toFixed(2) + '%'
    progress(str)
    if (str === '100.00%') {
      if (filePath.indexOf('http://59.110.170.159:9000') > -1){
        filePath = filePath.replace('http://59.110.170.159:9000','https://www.tonann.cn/oss')
      }
      if (filePutUrl.indexOf('http://59.110.170.159:9000') > -1){
        filePutUrl = filePutUrl.replace('http://59.110.170.159:9000','https://www.tonann.cn/oss')
      }
      success({path: filePath, url: filePutUrl})
    }
  })
  // http.onload = () => {
  //   // eslint-disable-next-line no-mixed-operators
  //   if (http.status === 200 && http.status < 300 || http.status === 304) {
  //     try {
  //       console.log(http.responseURL, 'x')
  //     } catch (error) {
  //       console.log(error, 'error')
  //     }
  //   }
  // }
  http.open('PUT', filePutUrl, true)
  http.send(file)
}
